import os
from django import forms
from django.shortcuts import render, HttpResponse
from django.conf import settings

from app01 import models
from app01.utils.bootstrap import BootStrapForm, BootStrapModelForm


def upload_list(request):
    if request.method == "GET":
        return render(request, "upload_list.html")
    # 普通的POST {'username': ['京东'], 'avatar': ['报名照片.JPG']}

    # 前端POST后加上enctype="multipart/form-data"
    # 'username': ['京东']
    # print(request.POST)
    # {'avatar': [<InMemoryUploadedFile: 报名照片.JPG (image/jpeg)>]}
    # print(request.FILES)
    # print(file_object.name)# 获得文件名

    file_object = request.FILES.get("avatar")
    filename = request.POST.get("username") + ".png"
    f = open(filename, mode='wb')
    for chunk in file_object.chunks():  # 文件分块读取
        f.write(chunk)
    f.close()

    return HttpResponse("...")


class UpForm(BootStrapForm):
    name = forms.CharField(label="姓名")
    age = forms.IntegerField(label="年龄")
    img = forms.FileField(label="头像")


def upload_form(request):
    title = "Form上传"
    if request.method == "GET":
        form = UpForm()
        return render(request, "upload_form.html", {"form": form, "title": title})
    form = UpForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # {'name': '星星', 'age': 27, 'img': <InMemoryUploadedFile: 报名照片2.jpg (image/jpeg)>}
        # 1.读取图片内容，写入到文件夹中并获取文件路径
        image_object = form.cleaned_data.get("img")

        # file_path="day16/app01/static/images/{}".format(image_object.name)
        media_path = os.path.join(settings.MEDIA_ROOT, image_object.name)
        # media_path=os.path.join("media", image_object.name)
        print(media_path)
        f = open(media_path, mode='wb')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()

        # 2.将图片文件路径写入到数据库中
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            img=media_path,
        )

        # 读取到内容，自己处理每个字段
        return HttpResponse("...")
    return render(request, "upload_form.html", {"form": form, "title": title})


class UpModelForm(BootStrapModelForm):
    bootstrap_exclude_field = ['img']

    class Meta:
        model = models.City
        fields = "__all__"


def upload_model_form(request):
    """ 上传文件和数据（ModelForm） """
    title = "ModelForm文件上传"
    if request.method == "GET":
        form = UpModelForm()
        return render(request, 'upload_form.html', {'form': form, 'title': title})
    form = UpModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 对文件自动保存
        # 字段 + 上传路径写入到数据库
        form.save()
        return HttpResponse("成功上传")
    return render(request, 'upload_form.html', {'form': form, 'title': title})
